import Vue from 'vue';
import config from '@/api/server/config';
import axios from 'axios';
import { Toast,Indicator } from 'mint-ui';
import {isLogin} from '@/common/js/auth';
import store from "@/store/index";
import router from "@/router";
/**
 * 请求服务端接口
 * @param url string 请求地址
 * @param params object 参数
 * @param method string 请求类型
 * @param loading bool 是否显示加载loading 默认显示
 */
export default function requestServer (url, params = null, loading = false, method = 'post') {
  let host = `${config.API}/${url}`;

  let parameter = {};
  params && (parameter = params);
  if(isLogin()){
    parameter.token = store.getters.token;
    parameter.userId = store.getters.userId;
  }
  const p = new Promise((resolve, reject) => {
    if (loading) Indicator.open();
    axios({
      method: method,
      url: host,
      data: parameter
    }).then((rs) => {
      let data = rs.data;
      if(data.code === config.ERR_OK){
        resolve(data.data);
      } else if(data.code === config.ERR_OUT_LOGIN) {
        store.dispatch('outLogin').then(()=>{
          router.push('/login');
        });
        reject(data.response_message);
      } else {
        reject(data.response_message);
      }
      if (loading) Indicator.close();
    }).catch((err)=>{
      // 请求出错
      if (loading) Indicator.close();
      let instance = Toast(err);
      setTimeout(() => {
        instance.close();
      }, 2000);

    })
  });
  return p;
}
